<template>
  <div class="management">
    <div class="mains_contain">
      <el-form :inline="true" size="small" label-width="80px">
        <el-form-item>
          <el-button type="primary" @click="handlerAdd()" icon="el-icon-plus" size="mini" v-has="['role:add']">新增</el-button>
        </el-form-item>
        <el-form-item label="租户">
          <el-select v-model="searchForm.tenantId" style="width: 100%" placeholder="请选择" clearable>
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" clearable placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlerSearch" icon="el-icon-search" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="contant">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <el-table-column prop="tenantTxt" label="租户" />
          <el-table-column prop="code" label="角色编码" />
          <el-table-column prop="name" label="角色名称" />

          <el-table-column prop="description" label="描述" />
          <el-table-column prop="loginTime" label="创建时间">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="100">
            <template slot-scope="{ row }">
              <el-button type="text" size="mini" @click="handlerUser(row)" icon="el-icon-user">用户</el-button>
              <el-button type="text" size="mini" @click="handlerUpdate(row)" icon="el-icon-edit" v-has="['role:edit']">修改</el-button>
              <el-button type="text" size="mini" @click="handleAuth(row)" v-has="['role:authorize']" icon="el-icon-setting">授权</el-button>
              <el-button type="text" style="color: #f56c6c" size="mini" icon="el-icon-delete" @click="handleDelete(row)" v-has="['role:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" @close="cancle" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px" :inline="false" size="small" :rules="rules">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="form.tenantId" style="width: 100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" clearable />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" clearable />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="primary" @click="handlerSave" size="small">保存</el-button>
        <el-button @click="cancle" size="small">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="用户" :visible.sync="userdialogVisible" width="70%" :close-on-click-modal="false">
      <el-form :inline="true" size="small" label-width="100px">
        <el-form-item>
          <el-button type="primary" @click="checkUsers" icon="el-icon-plus" size="mini">关联用户</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" size="mini" @click="allDelete" icon="el-icon-delete">批量解除关联</el-button>
        </el-form-item>
      </el-form>
      <div class="contant">
        <el-table :data="checktableDataUser" style="width: 100%" @selection-change="SelectionChangeCheck" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="username" label="账号" sortable />
          <el-table-column prop="realName" label="姓名" sortable />
          <!-- <el-table-column prop="tenantTxt" label="租户" sortable /> -->
          <el-table-column prop="status" label="状态" sortable>
            <template slot-scope="scope">
              <span style="color: #f56c6c" v-if="scope.row.status == '0'">冻结</span>
              <span style="color: #67c23a" v-if="scope.row.status == '1'">正常</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" sortable>
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center">
            <template slot-scope="{ row, $index }">
              <el-button type="text" size="mini" style="margin-right: 10px" @click="handleDeleteUser(row)" icon="el-icon-delete">解除关联</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination2.total > 0" :limit.sync="pagination2.pageSize" :page.sync="pagination2.pageNo" :total="pagination2.total" @pagination="getPageUser" />
        </div>
      </div>
      <!-- <div style="text-align: right;margin-top:20px">
        <el-button type="primary" @click="handlerSave" size="small"
          >保存</el-button
        >
        <el-button @click="userdialogVisible= false" size="small">取消</el-button>
      </div> -->
    </el-dialog>
    <el-dialog title="关联用户" :visible.sync="userdialogVisibleGan" width="70%" :close-on-click-modal="false">
      <el-form :inline="true" size="small" label-width="100px">
        <el-form-item label="姓名：">
          <el-input v-model="forms.username" clearable placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="guanSearch" icon="el-icon-search" size="mini">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="contant">
        <el-table :data="tableDataUser" style="width: 100%" @selection-change="handleSelectionChangeUser" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }" ref="tableUsers">
          <el-table-column type="selection" width="40" />
          <el-table-column prop="username" label="账号" sortable />
          <el-table-column prop="realName" label="姓名" sortable />
          <!-- <el-table-column prop="tenantTxt" label="租户" sortable /> -->
          <el-table-column prop="status" label="状态" sortable>
            <template slot-scope="scope">
              <span style="color: #f56c6c" v-if="scope.row.status == '0'">冻结</span>
              <span style="color: #67c23a" v-if="scope.row.status == '1'">正常</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" sortable>
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination1.total > 0" :limit.sync="pagination1.pageSize" :page.sync="pagination1.page" :total="pagination1.total" @pagination="getPageListUser" />
        </div>
      </div>
      <div style="text-align: right">
        <el-button type="primary" @click="handlerSaveCheck" size="small">保存</el-button>
        <el-button @click="userdialogVisibleGan = false" size="small">取消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="角色授权" :visible.sync="drawer" direction="rtl" class="drawers" style="overflow: scroll">
      <div style="padding: 10px">
        <el-tree class="tree-style" :data="authList" default-expand-all show-checkbox node-key="value" :props="defaultProps" ref="tree" :check-strictly="checkFlg"></el-tree>
        <div style="text-align: right; margin-top: 10px">
          <el-button type="primary" @click="handlerAuthSave" size="small">保存</el-button>
          <el-button @click="drawer = false" size="small">取消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as api from "@/api/sys/role";
import * as menuApi from "@/api/sys/menu";
import * as tenantApi from "@/api/sys/tenant";
import * as userApi from "@/api/sys/user";

export default {
  comments: {},
  props: {},
  inject: ['reload'],
  data() {
    return {
      forms: {},
      searchForm: {},
      title: "",
      dialogVisible: false,
      drawer: false,
      form: {},
      multipleSelection: [],
      tableData: [],
      tableDataUser: [],
      checktableDataUser: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      pagination1: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      pagination2: {
        total: 1,
        pageNo: 1,
        pageSize: 10,
      },
      rules: {
        tenantId: [{ required: true, message: "请选择租户", trigger: "blur" }],
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
      },
      authList: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
      checkFlg: false,
      roleId: null,
      lastPermissionIds: [],
      tenantList: [],
      userdialogVisible: false,
      checkUser: false,
      userdialogVisibleGan: false,
      checkUserList: [],
      userIds: [],
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
    checkList() {
      let listAll = [];
      this.checkUserList.forEach((item) => {
        listAll.push(item.id);
      });
      return listAll;
    },
  },
  created() {
    this.getPageList();
    this.getqueryTreeList();
    this.getTenantList();
  },
  mounted() { },
  methods: {
    handlerSaveCheck() {
      if (!this.checkList.length) {
        this.$message({
          type: "warning",
          message: "请至少选择一个用户",
        });
        return;
      } else {
        let data = {
          roleId: this.roleId,
          userIdList: this.checkList,
        };
        api.addSysUserRole(data).then((res) => {
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: res.message,
            });
            this.userdialogVisibleGan = false;
            this.getUserList();
            this.$refs.tableUsers.clearSelection();
          }
        });
      }
    },
    handleDeleteUser(row) {
      console.log(row);
      this.$confirm("是否解除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            roleId: this.roleId,
            userId: row.id,
          };
          api.deleteUserRole(data).then((resp) => {
            if (resp.code == "200") {
              this.$message({
                type: "success",
                message: "解除成功!",
              });
              if (
                (this.pagination2.total - 1) % this.pagination2.pageSize ==
                0
              ) {
                if (this.pagination2.page > 1) {
                  this.pagination2.page = this.pagination2.page - 1;
                }
              }
              this.getUserList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    SelectionChangeCheck(val) {
      console.log(val);
      this.userIds = val;
    },
    allDelete() {
      if (!this.userIds.length) {
        this.$message({
          type: "warning",
          message: "请至少选择一个用户!",
        });
      } else {
        let list = [];
        this.userIds.forEach((item) => {
          list.push(item.id);
        });
        let data = {
          roleId: this.roleId,
          userIds: list.join(","),
        };
        api.deleteUserRoleBatch(data).then((res) => {
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: "解除成功!",
            });
            if ((this.pagination2.total - 1) % this.pagination2.pageSize == 0) {
              if (this.pagination2.page > 1) {
                this.pagination2.page = this.pagination2.page - 1;
              }
            }
            this.getUserList();
          }
        });
      }
    },
    handleSelectionChangeUser(val) {
      this.checkUserList = val;
    },
    checkUsers() {
      this.userdialogVisibleGan = true;
      this.userList();
    },
    handlerUser(row) {
      console.log(row);
      this.roleId = row.id;
      this.userdialogVisible = true;
      this.getUserList();
    },
    getUserList() {
      let p = Object.assign({}, { roleId: this.roleId }, this.pagination2);
      api.userRoleList(p).then((res) => {
        console.log(res);
        this.checktableDataUser = res.data.list;
        this.pagination2.total = res.data.pagination.total;
      });
    },
    getPageUser() {
      this.getUserList();
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    cancle() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
      this.form = {}
    },
    // 获取全部的权限树
    getqueryTreeList() {
      menuApi.queryTreeList().then((res) => {
        this.authList = res.data.treeList;
      });
    },
    handlerAuthSave() {
      var idArr = this.$refs.tree
        .getHalfCheckedKeys()
        .concat(this.$refs.tree.getCheckedKeys());
      // console.log(idArr, '==勾选数据==');
      if (!this.roleId) {
        this.$message({
          message: "角色id不能为空",
          type: "warning",
        });
        return;
      }
      var AuthData = {
        roleId: this.roleId,
        permissionIds: idArr.join(","),
        lastPermissionIds: this.lastPermissionIds.join(","),
      };
      menuApi.saveRolePermission(AuthData).then((res) => {
        this.drawer = false;
        this.$store.dispatch("editRouters");
        setTimeout(() => {
          // this.reload()
          this.$router.go(0)
        }, 500)
      });
    },
    // 查询
    handlerSearch() {
      this.search();
    },
    // 复选框事件
    handleSelectionChange(val) {
      // this.multipleSelection = val;
    },
    getPageList() {
      this.search();
    },
    getPageListUser(limit) {
      console.log(limit);
      this.userList();
    },
    guanSearch() {
      this.userList()
    },
    userList() {
      let data = {
        roleId: this.roleId,
        username: this.forms.username,
        pageNo: this.pagination1.page,
        pageSize: this.pagination1.pageSize,
      };
      // let p = Object.assign({}, this.pagination1);
      api.userNotJoinRole(data).then((resp) => {
        console.log(resp);
        this.tableDataUser = resp.data.list;
        this.pagination1.total = resp.data.pagination.total;
      });
    },
    search() {
      if (this.searchForm.name == "") {
        this.searchForm.name = null;
      }
      const p = Object.assign({}, this.pagination, this.searchForm);
      api.page(p).then((resp) => {
        console.log(resp);
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    handlerAdd() {
      this.title = "新增";
      this.dialogVisible = true;
      this.form = {};
    },
    handlerUpdate(row) {
      this.title = "修改";
      this.dialogVisible = true;
      this.form = Object.assign({}, row);
    },
    handleAuth(row) {
      this.roleId = row.id;
      this.drawer = true;
      this.checkFlg = true;
      menuApi.queryRolePermission({ roleId: row.id }).then((resp) => {
        console.log(resp.data);
        var defaultAuth = resp.data;
        if (defaultAuth) {
          this.lastPermissionIds = defaultAuth;
          this.$nextTick(() => {
            // console.log(defaultAuth, '==回显数据==');
            this.$refs.tree.setCheckedKeys(defaultAuth);
            this.checkFlg = false;
          });
        } else {
          this.lastPermissionIds = [];

          this.$nextTick(() => {
            this.checkFlg = false;
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteId(row.id).then((resp) => {
            this.$message({
              type: "success",
              message: resp.message,
            });
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handlerSave() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            let data = {
              roleCode: this.form.code,
              id: this.form.id,
              tenantId: this.form.tenantId,
            };
            api.checkRoleCode(data).then((res) => {
              if (res.message == "false") {
                this.$message({
                  type: "warning",
                  message: "角色编码已经存在",
                });
                return;
              } else {
                api.update(this.form).then((resp) => {
                  this.dialogVisible = false;
                  this.getPageList();
                });
              }
            });
          } else {
            let data = {
              tenantId: this.form.tenantId,
              roleCode: this.form.code,
              id: "",
            };
            api.checkRoleCode(data).then((res) => {
              console.log(res);
              if (res.message == "false") {
                this.$message({
                  type: "warning",
                  message: "角色编码已经存在",
                });
                return;
              } else {
                api.save(this.form).then((resp) => {
                  this.dialogVisible = false;
                  this.getPageList();
                });
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss">
.management {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
.drawers {
  height: 100%;
}
.el-drawer__body {
  overflow-y: scroll !important;
}
.drawers {
  overflow: auto;
  flex: 1;
  height: cacl(100% -30px);
  >>> .el-tree-node {
    > .el-tree-node__children {
      overflow: visible !important;
    }
  }
}
</style>
